package com.jinpeng.websocket.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ProjectName: websocket
 * @Package: com.jinpeng.websocket.config
 * @ClassName: WebSocketServer
 * @Description: java类作用描述
 * @Author: 唐朝
 * @CreateDate: 2019/12/20 17:04
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/12/20 17:04
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@ServerEndpoint("/websocket/{sender}/{recipient}")
@Component
@Slf4j
public class WebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //接收sid
    private String sid="";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("sender") String sid) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
        try {
            //返回前端链接成功消息，也可以不返回，只做异常处理
            sendMessage("连接成功");
        } catch (IOException e) {

            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口"+sid+"的信息:"+message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage("收到来自窗口"+sid+"的信息:"+message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText("接到系统群发消息："+message);
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message,@PathParam("sender") String sid,@PathParam("recipient") String rid) {
        log.info("推送消息到窗口"+sid+"，推送内容:"+message);
        //不给推送人发送消息，避免重复接收
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个rid的，为null则全部推送
                if(rid==null&&!sid.equals(item.sid)) {
                    item.sendMessage("收到来自窗口"+sid+"的群发信息："+message);
                }
                if(item.sid.equals(rid)){
                    item.sendMessage("接到来自"+sid+"的私人消息："+message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }
    /**
     * 关闭某个用户的连接
     *
     * @param sid
     */
    public static void closeUserSocket(String sid) {
        Iterator<WebSocketServer> entries = webSocketSet.iterator();
        while(entries.hasNext()){
            WebSocketServer entry = entries.next();
            String key = entry.sid;
            if (key.equals(sid)){
                Session webSocketSession = entry.session;
                try {
                    webSocketSession.close();
                    webSocketSet.remove(webSocketSession);
                    log.info("关闭连接的userId:{}",sid);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }

    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
